package com.cjk.foundation.util;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.lang.time.DateFormatUtils;

import com.eaio.uuid.UUIDGen;

public class UUIDUtil {

	private static final char[] CHAR_TABLES_62 = "$0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
			.toCharArray();
	private static final AtomicLong seq = new AtomicLong(0L);
	private static final String NODE_SEQ_62;

	static {
		long nodeId = UUIDGen.getClockSeqAndNode();
		NODE_SEQ_62 = toChars(nodeId, CHAR_TABLES_62);
	}

	public static String nextOrderUUID() {
		NumberFormat format = new DecimalFormat("00000000");
		String currentSeq = format.format(getNextLocalSeq() % 100000000L);
		StringBuilder sb = new StringBuilder();
		sb.append(NODE_SEQ_62);
		sb.append(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
		sb.append(currentSeq);
		return sb.toString();
	}

	private static long getNextLocalSeq() {
		long temp;
		do {
			long incrementAndGet = seq.incrementAndGet();
			if (incrementAndGet > 0L) {
				return incrementAndGet;
			}
			temp = incrementAndGet + 9223372036854775807L;
		} while (temp <= 0L);
		return temp;
	}

	private static String toChars(long longValue, char[] charTables) {
		int length = charTables.length - 1;
		int[] charIndexTable = new int[16];
		for (int i = charIndexTable.length - 1; i > 0; i--) {
			if (longValue == 0L) {
				break;
			}
			int mod = (int) (longValue % length);
			if (mod < 0) {
				mod = -mod;
			}
			charIndexTable[i] = (mod + 1);

			longValue /= length;
		}
		StringBuilder sb = new StringBuilder();
		boolean firstNotZero = false;
		for (int i = 0; i < charIndexTable.length; i++) {
			int indexValue = charIndexTable[i];
			char currentChar = charTables[indexValue];
			if ((currentChar != '$') || (firstNotZero)) {
				firstNotZero = true;
				sb.append(currentChar);
			}
		}
		return sb.toString();
	}
	
	public static void main(String[] args){
		System.out.println(nextOrderUUID().length());
		System.out.println(new Date().getTime());
	}
}
